import os
import threading
import time

count = 0

# data = os.system(f"ping -n4 {ip} >/dev/null 2>/dev/null")    linux命令
def ping_host(ip):
    "我可以扫描一个ip的存活性"
    global count
    data = os.system(f"ping -n 4 {ip} >nul")  #windows命令
    if data == 0:
        print(f"The host {ip} is up")
        with open("uphost.txt", "a") as f:
            f.write(f"The host {ip} is up.\n")
        count += 1


def ping_net():
    "我可以扫描一个网段下ip的存活性"
    net = input("请输入一个网段，如：《10.1.1.》：")
    start = int(input("请输入测试IP的开始："))
    end = int(input("请输入测试IP的结束：")) + 1
    threads = []
    startTime = time.time()
    for i in range(start, end):
        ip = net + str(i)
        t = threading.Thread(target=ping_host, args=(ip,))
        threads.append(t)
        t.start()
    for j in threads:
        j.join()
    endTime = time.time()
    print(f"主机扫描完毕，共{count}主机在线!,共花费了{endTime - startTime:.3f}秒")


if __name__ == '__main__':
    ping_net()
